<template>
  <el-dialog
    class="dictionary-dialog"
    :title="mode === 'add' ? '新增字典数据' : '编辑字典数据'"
    :model-value="visible"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="140px"
      label-position="right"
    >
      <el-form-item v-if="mode === 'add'" label="字典类型" prop="typeKey">
        <el-input v-model="form.typeKey" readonly style="width: 300px" />
      </el-form-item>
      <el-form-item label="字典键" prop="dataKey">
        <el-input
          v-model="form.dataKey"
          :readonly="mode === 'edit'"
          :disabled="mode === 'edit'"
          placeholder="请输入字典键"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="字典描述" prop="value">
        <el-input
          v-model="form.value"
          placeholder="请输入字典描述"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="父级字典" prop="parentDataKey">
        <el-select
          v-model="form.parentDataKey"
          placeholder="请选择父级字典（可选）"
          clearable
          style="width: 300px"
        >
          <el-option
            v-for="item in parentOptions"
            :key="item.dataKey"
            :label="`${item.value} (${item.dataKey})`"
            :value="item.dataKey"
            :disabled="item.dataKey === form.dataKey"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <div style="display: flex; align-items: center; gap: 10px;">
          <el-upload
            ref="iconUploadRef"
            :show-file-list="false"
            :before-upload="handleIconUpload"
            accept="image/*"
            :disabled="iconUploading"
          >
            <el-button type="primary" :loading="iconUploading">
              {{ iconUploading ? '上传中...' : '上传图标' }}
            </el-button>
          </el-upload>
          <el-button v-if="form.icon" type="danger" @click="removeIcon">
            移除图标
          </el-button>
        </div>
        <div v-if="form.icon" style="margin-top: 10px;">
          <el-image
            :src="form.icon"
            style="width: 60px; height: 60px"
            fit="cover"
            :preview-src-list="[form.icon]"
          />
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注（可选）"
          :rows="2"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="1"
          :max="9999"
          style="width: 300px"
          :controls="false"
          placeholder="请输入排序（可选）"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="停用"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          {{ mode === 'add' ? '确定' : '更新' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { uploadIcon, getDictionaryDataByTypeKey } from '@/api/dictionary'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean,
  mode: { type: String, default: 'add' }, // 'add' | 'edit'
  data: { type: Object, default: () => ({}) },
  typeKey: { type: String, default: '' },
  allData: { type: Array, default: () => [] } // 传入所有字典数据用于父级选择
})
const emits = defineEmits(['update:visible', 'submit'])

const formRef = ref(null)
const form = ref({
  typeKey: '',
  dataKey: '',
  value: '',
  parentDataKey: '',
  remark: '',
  sort: undefined,
  status: 1,
  icon: ''
})

const rules = {
  dataKey: [{ required: true, message: '请输入字典键', trigger: 'blur' }],
  value: [{ required: true, message: '请输入字典描述', trigger: 'blur' }]
}

// 父级字典选项（过滤掉自己，避免循环引用）
const parentOptions = computed(() => {
  return props.allData.filter(item => {
    // 过滤掉自己
    if (item.dataKey === form.value.dataKey) return false
    // 如果是编辑模式，还需要过滤掉以当前项为父级的子项，避免循环引用
    if (props.mode === 'edit') {
      return !isChildOf(item.dataKey, form.value.dataKey)
    }
    return true
  })
})

// 检查是否是某个节点的子节点（递归检查，防止循环引用）
const isChildOf = (childDataKey, parentDataKey) => {
  const child = props.allData.find(item => item.dataKey === childDataKey)
  if (!child || !child.parentDataKey) return false
  if (child.parentDataKey === parentDataKey) return true
  return isChildOf(child.parentDataKey, parentDataKey)
}

// 图标上传相关
const iconUploadRef = ref(null)
const iconUploading = ref(false)

// 处理图标上传
const handleIconUpload = async (file) => {
  try {
    iconUploading.value = true
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await uploadIcon(formData)
    form.value.icon = res.url
    ElMessage.success('图标上传成功')
  } catch (error) {
    console.error('图标上传失败:', error)
    ElMessage.error('图标上传失败')
  } finally {
    iconUploading.value = false
  }
}

// 移除图标
const removeIcon = () => {
  form.value.icon = ''
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (props.mode === 'edit') {
        form.value = { ...props.data }
      } else {
        form.value = {
          typeKey: props.typeKey,
          dataKey: '',
          value: '',
          parentDataKey: '',
          remark: '',
          sort: undefined,
          status: 1,
          icon: ''
        }
      }
    }
  }
)

function handleClose() {
  emits('update:visible', false)
}

function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      emits('submit', { ...form.value })
      handleClose()
    }
  })
}
</script>

<style scoped lang="scss">
.dictionary-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 20px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  :deep(.el-dialog__body) {
    padding: 30px 20px;
  }
  
  :deep(.el-dialog__footer) {
    padding: 0 20px 20px;
    border-top: 1px solid #f0f0f0;
  }
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-title {
  font-size: 18px;
  font-weight: normal !important;
  color: #333;
  text-align: center;
  width: 100%;
  display: block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}

:deep(.el-dialog__title) {
  font-weight: normal !important;
  text-align: center;
  width: 100%;
  display: block;
}
</style>